package cn.fl.institution.controller;

import cmm.mid.core.framework.page.DataResultVO;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.commons.result.ResponseData;
import cn.fl.customer.service.ICstNpBscInfoService;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.framework.constant.DictionaryConstant;
import cn.fl.preloan.constants.FinancialRequestConstants;
import cn.fl.preloan.dto.financialinterface.PreCreditApplyRequest;
import cn.fl.preloan.dto.financialinterface.PreCreditApplyResponseDTO;
import cn.fl.preloan.enums.PreCreditStatusEnum;
import cn.fl.preloan.financialinterface.IFinancialService;
import cn.fl.project.condition.PrjCstAccInfoQueryCondition;
import cn.fl.project.service.IPrjCstAccInfoService;
import cn.fl.project.vo.PrjCstAccInfoVO;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @Description: 项目基础信息表 控制层浦发二期（spdbankde）
 */
@Controller
@RequestMapping("/institution/spdbankde")
public class PrjBscInfoInsSpdbankdeController {

    @Autowired
    private ICstNpBscInfoService cstNpBscInfoService;

    @Autowired
    private IPrjCstAccInfoService prjCstAccInfoService;

    @Autowired
    private IFinancialService financialService;

    /**
     * 保存 项目客户信息
     */
    @RequestMapping(value = "/saveForSpdbankde.do", method = RequestMethod.POST)
    @ResponseBody
    public DataResultVO saveForSpdbankde(HttpServletRequest request) throws BaseException {
        BaseLogUtils.newLogger("修改项目客户账户信息：" + JSON.toJSONString(request.getParameterMap()) + "，操作人：" + CurrentThreadContext.getCurrentUserName()).info();
        String cstAccInfoId = request.getParameter("cstAccInfoId");
        String insCode = request.getParameter("insCode");
        String prjId = request.getParameter("prjId");
        String cstId = request.getParameter("cstId");
        String cstNm = request.getParameter("cstNm");
        String certNo = request.getParameter("certNo");
        String monthInc = request.getParameter("monthInc");
        String highDgCd = request.getParameter("highDgCd");

        DataResultVO dataResultVO = new DataResultVO(BaseConstant.IS_YESNO_YES, "保存成功");
        try {
            if (StringUtils.isEmpty(prjId)) {
                return new DataResultVO(BaseConstant.IS_YESNO_NO, "项目id为空!");
            }
            if (StringUtils.isEmpty(cstId)) {
                return new DataResultVO(BaseConstant.IS_YESNO_NO, "客户id为空!");
            }
            if (StringUtils.isEmpty(cstNm)) {
                return new DataResultVO(BaseConstant.IS_YESNO_NO, "客户名称为空!");
            }
            if (StringUtils.isEmpty(monthInc)  || !StringUtils.isUnsignedNumeric(monthInc)) {
                return new DataResultVO(BaseConstant.IS_YESNO_NO, "请维护月收入!");
            }
            if (StringUtils.isEmpty(highDgCd)) {
                return new DataResultVO(BaseConstant.IS_YESNO_NO, "请维护学历!");
            }
            PrjCstAccInfoVO vo = new PrjCstAccInfoVO();
            PreCreditApplyRequest preCreditApplyRequest = new PreCreditApplyRequest();
            preCreditApplyRequest.setBizSN(prjId);
            preCreditApplyRequest.setInsCode(insCode);
            preCreditApplyRequest.setSourceCode(FinancialRequestConstants.SOURCE_CODE_PRE_CREDIT_APPLY);
            BaseLogUtils.newLogger("=预授信申请开始=preCreditApplyRequest:{}", JSONObject.toJSONString(preCreditApplyRequest)).info();
            ResponseData<PreCreditApplyResponseDTO> responseData = financialService.preCreditApply(preCreditApplyRequest);
            BaseLogUtils.newLogger("=预授信申请结束=responseData:{}", JSON.toJSONString(responseData)).info();
            if (null == responseData) {
                dataResultVO.setSuccess(0);
                dataResultVO.setInfo("准入失败，返回结果为空！");
            } else if (!responseData.isSuccess() || !ResponseData.SUCCESS_CODE.equals(responseData.getCode()) || null == responseData.getData()) {
                dataResultVO.setSuccess(0);
                if (StringUtils.isNotEmpty(responseData.getMessage())) {
                    dataResultVO.setInfo(responseData.getMessage());
                    return dataResultVO;
                }
            } else {
                PreCreditApplyResponseDTO data = responseData.getData();
                if (PreCreditStatusEnum.AUDIT_REJECT.getCode().equals(data.getPreCreditStatus())){
                    dataResultVO.setSuccess(0);
                    if (null != data.getPreCreditDesc()){
                        dataResultVO.setInfo(data.getPreCreditDesc());
                        return dataResultVO;
                    }
                } else if (PreCreditStatusEnum.AUDIT_PASS.getCode().equals(data.getPreCreditStatus())) {
                    vo.setAccessRstCd(data.getPreCreditStatus());
                }
            }
            // 修改项目客户信息
            PrjCstAccInfoQueryCondition condition = new PrjCstAccInfoQueryCondition();
            if (StringUtils.isNotEmpty(cstAccInfoId)) {
                condition.setId(Long.valueOf(cstAccInfoId));
            }
            condition.setPrjId(Long.valueOf(prjId));
            condition.setCstId(Long.valueOf(cstId));
            condition.setInsCode(insCode);
            condition.setCstNm(cstNm);
            condition.setAccNm(cstNm);
            condition.setCertNo(certNo.trim());
            condition.setCertTypCd(DictionaryConstant.CODE_CERT_TYP_CD_0);
            condition.setMonthInc(monthInc);
            condition.setHighDgCd(highDgCd);
            boolean modify = this.cstNpBscInfoService.modifyCstNpBscInfo(condition);

            vo.setPrjId(Long.valueOf(prjId));
            vo.setCstId(Long.valueOf(cstId));
            vo.setInsCode(insCode);
            vo.setCstNm(cstNm);
            vo.setAccNm(cstNm);
            vo.setCertNo(certNo.trim());
            vo.setCertTypCd(DictionaryConstant.CODE_CERT_TYP_CD_0);
            BaseLogUtils.newLogger("修改项目客户账户信息,cstAccInfoId:{},condition:{}",cstAccInfoId, JSONObject.toJSONString(vo)).info();
            if (StringUtils.isNotEmpty(cstAccInfoId)) {
                vo.setId(Long.valueOf(cstAccInfoId));
                dataResultVO.setData(cstAccInfoId);
                boolean flag = prjCstAccInfoService.modify(vo);
                BaseLogUtils.newLogger("修改项目客户账户信息,flag:{},cstAccInfoId:{}",flag,cstAccInfoId).info();
                if (false == flag) {
                    dataResultVO.setSuccess(BaseConstant.IS_YESNO_NO);
                    dataResultVO.setInfo("修改项目客户账户信息失败");
                }
            } else {
                Long add = prjCstAccInfoService.add(vo);
                dataResultVO.setData(add);
            }

        } catch (BaseException ex) {
            dataResultVO.setSuccess(BaseConstant.IS_YESNO_NO);
            dataResultVO.setInfo(ex.getMessage());
            BaseLogUtils.newLogger("保存项目客户账户信息及校验,prjId:" + prjId + ".ERROR:" + ex.getMessage()).info();
        } catch (Exception e) {
            BaseLogUtils.newLogger("保存失败，系统异常" + e).info();
            return new DataResultVO(BaseConstant.IS_YESNO_NO, "保存失败，系统异常");
        }
        BaseLogUtils.newLogger("保存项目客户账户信息及校验返回dataResultVO=" + JSON.toJSONString(dataResultVO)).info();
        return dataResultVO;
    }
}
